<script setup>
import { ref } from 'vue'
import { User, Lock } from '@element-plus/icons-vue'
import { userLoginService } from '@/api/user'
import { useUserStore } from '@/stores'
import { useRouter } from 'vue-router'

const form = ref()

// 登录
const formModel = ref({
  username: '',
  password: '',
})

const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
}

const userStore = useUserStore()
const router = useRouter()
const login = async () => {
  await form.value.validate()
  const res = await userLoginService(formModel.value)
  userStore.setToken(res.data.data)
  router.push('/')
}
</script>

<template>
  <!-- 
  el-row：一行（一行分成24份）
  el-col：一列
    （1）:span="12" 代表在一行中占12份[50%]
    （2）:offset="3" 代表在一行中, 左侧margin占3份
  el-form：整个表单组件
  el-form-item：表单的一行（一个表单域）
  el-input：表单元素

  （1）el-form => :model="ruleForm" 绑定整个form的数据对象
  （2）el-form => :rules="rules" 绑定整个rules规则对象
  （3）表单元素 => v-model="ruleForm.xxx" 给表单元素, 绑定form的子属性
  （4）el-form-item => prop 配置生效的是哪个校验规则 
  -->

  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <!-- 登录表单 -->
      <el-form :model="formModel" :rules="rules" ref="form" size="large" autocomplete="off" @submit.prevent>
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="username">
          <el-input
            v-model="formModel.username"
            @keyup.enter="login"
            :prefix-icon="User"
            placeholder="用户名"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="formModel.password"
            @keyup.enter="login"
            name="password"
            :prefix-icon="Lock"
            type="password"
            placeholder="密码"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="login" class="button" type="primary" auto-insert-space>
            登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background-color: #fff;
  .bg {
    background:
      url('@/assets/mt_logo.png') no-repeat 50% center / 240px auto,
      url('@/assets/login_bg.png') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }
  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;
    .title {
      margin: 0 auto;
    }
    .button {
      margin-top: 20px;
      width: 100%;
    }
  }
  .flex {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
}
</style>
